package com.tqyan.start.controller;

import com.tqyan.model.Result;
import com.tqyan.model.controller.request.ChatRequest;
import com.tqyan.model.controller.response.ChatContentResp;
import com.tqyan.model.controller.response.ChatResp;
import com.tqyan.model.exp.DefaultException;
import com.tqyan.model.mapping.ChatAssembler;
import com.tqyan.service.service.ChatChatService;
import com.tqyan.service.service.ChatDrawService;
import com.tqyan.service.service.ChatService;
import com.tqyan.service.transfer.FileService;
import com.tqyan.service.transfer.LimitService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @description 会话API
 * <p> <功能详细描述> </p>
 *
 * @author 陈晨
 * @date 2023/4/11 17:20
 */
@RestController
@RequestMapping("/chat/")
@Slf4j
//@Api(tags = "会话API")
public class ChatController {

    @Autowired
    private ChatAssembler chatAssembler;
    @Autowired
    private ChatService chatService;
    @Autowired
    private ChatChatService chatChatService;
    @Autowired
    private ChatDrawService chatDrawService;
    @Autowired
    private FileService fileService;
    @Autowired
    private LimitService limitService;

    @PostMapping("/getChatList")
//    @ApiOperation(value = "获取聊天列表")
    public Result<List<ChatResp>> getChatList(@RequestBody ChatRequest chatRequest) {
        if (null == chatRequest
                || StringUtils.isBlank(chatRequest.getOpenId())) {
            return Result.fail("请求参数不可为空");
        }
//        log.info("[会话-聊天] chatRequest={}, 获取聊天列表", chatRequest);
        try {
            return Result.success(chatAssembler.convertChat(
                    chatService.getChatList(chatRequest.getOpenId())));
        } catch (Exception e) {
            log.error("[会话-聊天] chatRequest={}, 获取聊天列表, 异常: {}"
                    , chatRequest, e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping("/chatDelete")
//    @ApiOperation(value = "删除会话")
    public Result<Void> chatDelete(@RequestBody ChatRequest chatRequest) {
        if (null == chatRequest
                || StringUtils.isBlank(chatRequest.getOpenId())
                || null == chatRequest.getChatId()) {
            return Result.fail("请求参数不可为空");
        }
        log.info("[会话-聊天] chatRequest={}, 删除会话", chatRequest);
        try {
            chatService.delete(chatRequest.getOpenId(), chatRequest.getChatId());
            return Result.success();
        } catch (Exception e) {
            log.error("[会话-聊天] chatRequest={}, 删除会话, 异常: {}"
                    , chatRequest, e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping("/getChatContentList")
//    @ApiOperation(value = "获取聊天内容列表")
    public Result<List<ChatContentResp>> getChatContentList(@RequestBody ChatRequest chatRequest) {
        if (null == chatRequest
                || StringUtils.isBlank(chatRequest.getOpenId())
                || null == chatRequest.getChatId()) {
            return Result.fail("请求参数不可为空");
        }
//        log.info("[会话-聊天] chatRequest={}, 获取聊天内容列表", chatRequest);
        boolean isLock = limitService.lock(chatRequest.getOpenId());
        if (!isLock) {
            return Result.fail("让小燕子休息一会吧");
        }
        try {
            return Result.success(chatService.getChatContentList(chatRequest.getOpenId(), chatRequest.getChatId()));
        } catch (Exception e) {
            log.error("[会话-聊天] chatRequest={}, 获取聊天内容列表, 异常: {}"
                    , chatRequest, e.getMessage(), e);
            return Result.fail(e.getMessage());
        } finally {
            limitService.unlock(chatRequest.getOpenId());
        }
    }

    @PostMapping("/getChatContentListByDraw")
//    @ApiOperation(value = "获取绘画内容列表")
    public Result<List<ChatContentResp>> getChatContentListByDraw(@RequestBody ChatRequest chatRequest) {
        if (null == chatRequest
                || StringUtils.isBlank(chatRequest.getOpenId())) {
            return Result.fail("请求参数不可为空");
        }
//        log.info("[会话-绘画] chatRequest={}, 获取绘画内容列表", chatRequest);
        boolean isLock = limitService.lock(chatRequest.getOpenId());
        if (!isLock) {
            return Result.fail("让小燕子休息一会吧");
        }
        try {
            return Result.success(chatService.getChatContentListByDraw(chatRequest.getOpenId()));
        } catch (Exception e) {
            log.error("[会话-绘画] chatRequest={}, 获取绘画内容列表, 异常: {}"
                    , chatRequest, e.getMessage(), e);
            return Result.fail(e.getMessage());
        } finally {
            limitService.unlock(chatRequest.getOpenId());
        }
    }

    @PostMapping("/getChatContent")
//    @ApiOperation(value = "获取指定会话内容")
    public Result<ChatContentResp> getChatContent(@RequestBody ChatRequest chatRequest) {
        if (null == chatRequest
                || StringUtils.isBlank(chatRequest.getOpenId())
                || null == chatRequest.getChatId()
                || null == chatRequest.getChatContentId()) {
            return Result.fail("请求参数不可为空");
        }
//        log.info("[会话] chatRequest={}, 获取指定会话内容", chatRequest);
//        boolean isLock = limitService.lock(chatRequest.getOpenId());
//        if (!isLock) {
//            return Result.fail("让小燕子休息一会吧");
//        }
        try {
//            log.info("[获取指定会话内容] chatRequest={}", chatRequest);
            return Result.success(chatService.getChatContent(
                    chatRequest.getOpenId(), chatRequest.getChatId(), chatRequest.getChatContentId()));
        } catch (Exception e) {
            log.error("[会话] chatRequest={}, 获取指定会话内容, 异常: {}"
                    , chatRequest, e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
//        finally {
//            limitService.unlock(chatRequest.getOpenId());
//        }
    }

//    @PostMapping("/getChatSetting")
//    @ApiOperation(value = "获取会话设置")
//    public Result<ChatSettingDTO> getChatSetting(@RequestBody ChatRequest chatRequest) {
//        log.info("[会话] chatRequest={}, 获取会话设置", chatRequest);
//        try {
//            return Result.success(chatService.getChatSetting(
//                    chatRequest.getOpenId(), chatRequest.getChatId()));
//        } catch (Exception e) {
//            log.error("[会话] chatRequest={}, 获取会话设置, 异常: {}"
//                    , chatRequest, e.getMessage(), e);
//            return Result.fail(e.getMessage());
//        }
//    }
//
//    @PostMapping("/setModel")
//    @ApiOperation(value = "设置会话模式")
//    public Result<Void> setModel(@RequestBody ChatRequest chatRequest) {
//        log.info("[会话-设置] chatRequest={}, 设置会话模式", chatRequest);
//        try {
//            chatService.setModel(chatRequest.getOpenId(), chatRequest.getChatId(), chatRequest.getModel());
//            return Result.success();
//        } catch (Exception e) {
//            log.error("[会话-设置] chatRequest={}, 设置会话模式, 异常: {}"
//                    , chatRequest, e.getMessage(), e);
//            return Result.fail(e.getMessage());
//        }
//    }
//
//    @PostMapping("/setCreativeAbility")
//    @ApiOperation(value = "设置创造力")
//    public Result<Void> setCreativeAbility(@RequestBody ChatRequest chatRequest) {
//        log.info("[会话-设置] chatRequest={}, 设置创造力", chatRequest);
//        try {
//            chatService.setCreativeAbility(chatRequest.getOpenId(), chatRequest.getChatId(), chatRequest.getCreativeAbility());
//            return Result.success();
//        } catch (Exception e) {
//            log.error("[会话-设置] chatRequest={}, 设置创造力, 异常: {}"
//                    , chatRequest, e.getMessage(), e);
//            return Result.fail(e.getMessage());
//        }
//    }
//
//    @PostMapping("/setOpenAiKey")
//    @ApiOperation(value = "设置OpenAIKey")
//    public Result<Void> setOpenAiKey(@RequestBody ChatRequest chatRequest) {
//        log.info("[会话-设置] chatRequest={}, 设置OpenAIKey", chatRequest);
//        try {
//            chatService.setOpenAiKey(chatRequest.getOpenId(), chatRequest.getChatId(), chatRequest.getOpenAiKey());
//            return Result.success();
//        } catch (Exception e) {
//            log.error("[会话-设置] chatRequest={}, 设置OpenAIKey, 异常: {}"
//                    , chatRequest, e.getMessage(), e);
//            return Result.fail(e.getMessage());
//        }
//    }

    @PostMapping("/chat")
//    @ApiOperation(value = "聊天")
    public Result<ChatContentResp> chat(@RequestBody ChatRequest chatRequest) {
        if (null == chatRequest
                || StringUtils.isBlank(chatRequest.getOpenId())
                || null == chatRequest.getContent()) {
            return Result.fail("请求参数不可为空");
        }
        log.info("[会话-聊天] chatRequest={}, 聊天", chatRequest);
        boolean isLock = limitService.lock(chatRequest.getOpenId());
        if (!isLock) {
            return Result.fail("让小燕子休息一会吧");
        }
        try {
            ChatContentResp resp = chatChatService.chat(
                    chatRequest.getOpenId(), chatRequest.getChatId(), chatRequest.getContent());
//            log.info("[会话-聊天] chatRequest={}, chatResponse={}, 聊天响应", chatRequest, resp);
            return Result.success(resp);
        } catch (DefaultException e) {
            log.error("[会话-聊天] chatRequest={}, 聊天, 异常: {}"
                    , chatRequest, e.getMessage(), e);
            return Result.fail(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            log.error("[会话-聊天] chatRequest={}, 聊天, 异常: {}"
                    , chatRequest, e.getMessage(), e);
            return Result.fail(e.getMessage());
        } finally {
            limitService.unlock(chatRequest.getOpenId());
        }
    }

    @PostMapping("/draw")
//    @ApiOperation(value = "绘画")
    public Result<ChatContentResp> draw(@RequestBody ChatRequest chatRequest) {
        if (null == chatRequest
                || StringUtils.isBlank(chatRequest.getOpenId())
                || null == chatRequest.getContent()) {
            return Result.fail("请求参数不可为空");
        }
        log.info("[会话-绘画] chatRequest={}, 绘画", chatRequest);
        boolean isLock = limitService.lock(chatRequest.getOpenId());
        if (!isLock) {
            return Result.fail("让小燕子休息一会吧");
        }
        try {
            return Result.success(chatDrawService.draw(chatRequest.getOpenId(), chatRequest.getContent()));
        } catch (DefaultException e) {
            log.error("[会话-绘画] chatRequest={}, 绘画, 异常: {}"
                    , chatRequest, e.getMessage(), e);
            return Result.fail(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            log.error("[会话-绘画] chatRequest={}, 绘画, 异常: {}"
                    , chatRequest, e.getMessage(), e);
            return Result.fail(e.getMessage());
        } finally {
            limitService.unlock(chatRequest.getOpenId());
        }
    }

    @RequestMapping("/image/{fileName}")
    public Object download(HttpServletResponse response, @PathVariable String fileName) {
        return null;
//        try {
//            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
//            fileService.downloadAliyunOSS(response.getOutputStream(), FileService.FOLDER_DRAW_ORIGINAL, fileName);
//            return null;
//        } catch (Exception e) {
//            return e.getMessage();
//        }
    }

    @RequestMapping("/image/thumbnail/{fileName}")
    public Object downloadThumbnail(HttpServletResponse response, @PathVariable String fileName) {
        return null;
//        try {
//            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
//            fileService.downloadAliyunOSS(response.getOutputStream(), FileService.FOLDER_DRAW_THUMBNAIL, fileName);
//            return null;
//        } catch (Exception e) {
//            return e.getMessage();
//        }
    }

}


